<template>
  <view>
    <up-upload
      :file-list="fileList"
      name="image"
      multiple
      :deletable="deletable"
      :max-count="maxCount"
      :preview-full_image="true"
      @after-read="afterRead"
      @delete="deletePic"
    >
    </up-upload>
  </view>
</template>

<script setup lang="ts" name="ImageUpload">
import { globalHeaders } from '@/utils/request';
import { to } from 'await-to-js';

const props = defineProps({
  modelValue: {
    type: [String, Object, Array],
    default: () => []
  },
  //最大上传数量
  maxCount: {
    type: Number,
    default: 5
  },
  //是否开启上传
  disabled: {
    type: Boolean,
    default: true
  }
});
const uploadImgUrl = ref('/resource/oss/upload'); // 上传的图片服务器地址
const fileList = ref<any[]>([]);
const deletable = ref<boolean>(true);
const maxCount = ref<number>(props.maxCount);
const headers = ref(globalHeaders());
const emit = defineEmits(['update:modelValue']);
// 删除图片
const deletePic = (event: any) => {
  fileList.value.splice(event.index, 1);
  emit('update:modelValue', listToString(fileList.value));
};

// 新增图片
const afterRead = async (event: any) => {
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file);
  let fileListLen = fileList.value.length;
  lists.forEach((item: {}) => {
    fileList.value.push({
      ...item,
      status: 'uploading',
      message: '上传中'
    });
  });
  lists.forEach(async (item) => {
    const result = await uploadFilePromise(item.url);
    let lastItem = fileList.value[fileListLen];
    fileList.value.splice(fileListLen, 1, {
      ...lastItem,
      status: 'success',
      message: '',
      url: result.url,
      ossId: result.ossId
    });
    emit('update:modelValue', listToString(fileList.value));
    fileListLen++;
  });
};

const uploadFilePromise = async (url: any): Promise<{ url: any; ossId: any; }> => {
  const [err, res] = await to(
    uni?.$u?.http?.upload(
      uploadImgUrl.value,
      {
        filePath: url,
        name: 'file',
        header: headers.value
      }
    )
  );
  return res?.data;
};

// 对象转成指定字符串分隔
const listToString = (list: any[], separator ?: string) => {
  let strs = '';
  separator = separator || ',';
  for (let i in list) {
    if (undefined !== list[i].ossId && list[i].url.indexOf('blob:') !== 0) {
      strs += list[i].ossId + separator;
    }
  }
  return strs != '' ? strs.substring(0, strs.length - 1) : '';
};
const setData = async () => {
  if (!props.disabled) {
    deletable.value = false;
    maxCount.value = 0;
  }
  if (props.modelValue) {
    const res = await uni.$u.http.get(`/resource/oss/listByIds/${props.modelValue}`);
    fileList.value = res.data.map((item: { ossId: any; url: any; }) => {
      // 字符串回显处理 如果此处存的是url可直接回显 如果存的是id需要调用接口查出来
      let itemData;
      if (typeof item === 'string') {
        itemData = { name: item, url: item, status: 'success', message: '' };
      } else {
        // 此处name使用ossId 防止删除出现重名
        itemData = { name: item.ossId, url: item.url, ossId: item.ossId, status: 'success', message: '' };
      }
      return itemData;
    });
  }
};

watch(
  () => props.modelValue,
  async (val: string) => {
    if (val) {
      setData();
    }
  },
  { deep: true, immediate: true }
);

</script>
